import time

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from base_tools.my_logger import logger
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import traceback
from selenium.webdriver.common.action_chains import ActionChains

def init_driver():
    driver = webdriver.Chrome(ChromeDriverManager().install())
    # 设置浏览器最大化
    logger.info("设置浏览器最大化")
    driver.maximize_window()
    # 设置隐式等待，10s
    logger.info("设置隐式等待时长：10s")
    driver.implicitly_wait(10)
    return driver

class BasePage():

    def __init__(self, driver):
        """
        初始化基本页面对象
        """
        # 通过参数传入driver，实现浏览器驱动的传递，避免实例化不同的页面对象时，代码会反复的去初始化浏览器驱动
        # 初始化浏览器驱动
        logger.info("初始化页面对象。。。。")
        self.driver = driver


    def my_get(self, url):
        """
        打开指定url
        :return:
        """
        logger.info("打开url：{}".format(url))
        self.driver.get(url)

    def my_find_element(self, ele, time_out=10):
        """
        查找元素方法封装
        :param ele: 元组，例如：（'id', 'kw'）
        :param time_out:
        :return:
        """
        logger.info("查找元素：{}，超时时间：{}".format(ele, time_out))
        try:
            self.element = WebDriverWait(self.driver, time_out, 0.5).until(EC.presence_of_element_located(ele))
        except:
            logger.warning("元素定位失败，请检查，报错信息如下：", traceback.print_exc())
            raise Exception("元素定位失败")

    def my_click(self, ele, **kwargs):
        self.my_find_element(ele, **kwargs)
        logger.info("点击元素。。。。")
        self.element.click()

    def my_send_keys(self, ele, value, **kwargs):
        self.my_find_element(ele, **kwargs)
        logger.info("元素内输入文本：{}".format(value))
        self.element.clear()
        self.element.send_keys(value)

    def my_get_text(self, ele):
        """
        获取元素内文本信息
        :param ele:
        :return:
        """
        self.my_find_element(ele)
        return self.element.text

    def my_get_cookies(self):
        logger.info("获取当前页面cookies信息。。。。")
        self.cookies = self.driver.get_cookies()

    def my_add_cookies(self, cookies):
        logger.info("设置页面cookies：{}".format(cookies))
        for cookie in cookies:
            self.driver.add_cookie(cookie)
        self.driver.refresh()

    def my_move_to_element(self, ele, **kwargs):
        logger.info("鼠标悬停至指定元素：{}".format(ele))
        self.my_find_element(ele, **kwargs)
        ActionChains(self.driver).move_to_element(self.element).perform()

    def my_quit(self):
        logger.info("关闭浏览器。。。。")
        self.driver.quit()


# driver = init_driver()
# # 初始化页面对象
# page_obj = BasePage(driver=driver)
# # driver  = webdriver.Chrome(ChromeDriverManager().install())
# # page_obj.driver = driver
# # 打开企业微信首页
# page_obj.my_get("https://work.weixin.qq.com/wework_admin/frame#index")
# import time
# time.sleep(20)
# # 获取cookies
# page_obj.my_get_cookies()
# # 打印cookies信息
# print(page_obj.cookies)
# cookies = [{'domain': '.work.weixin.qq.com', 'httpOnly': True, 'name': 'wwrtx.logined', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': 'true'}, {'domain': '.work.weixin.qq.com', 'httpOnly': False, 'name': 'wwrtx.cs_ind', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': ''}, {'domain': '.work.weixin.qq.com', 'httpOnly': False, 'name': 'wxpay.vid', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': '1688858211371146'}, {'domain': '.work.weixin.qq.com', 'httpOnly': False, 'name': 'wxpay.corpid', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': '1970325261984975'}, {'domain': '.work.weixin.qq.com', 'httpOnly': False, 'name': 'wwrtx.vid', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': '1688858211371146'}, {'domain': '.work.weixin.qq.com', 'httpOnly': True, 'name': 'wwrtx.ref', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': 'direct'}, {'domain': '.work.weixin.qq.com', 'httpOnly': True, 'name': 'wwrtx.ltype', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': '1'}, {'domain': '.work.weixin.qq.com', 'httpOnly': False, 'name': 'wwrtx.d2st', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': 'a8564917'}, {'domain': '.work.weixin.qq.com', 'httpOnly': True, 'name': 'wwrtx.refid', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': '02246120'}, {'domain': '.work.weixin.qq.com', 'expiry': 1686573455, 'httpOnly': False, 'name': 'wwrtx.i18n_lan', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': 'zh'}, {'domain': '.work.weixin.qq.com', 'httpOnly': True, 'name': 'wwrtx.vst', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': 'kvIdADkFPLd3BNM-W6LnKhMkGUyp9M1MONNqRIqyFpBuXFqSnPoNOHaLNRzmRKJe5nJCsMwlTL_ZS86r1PaQKRI7xVoSTPJJ_4fY8cZrO5WB90N6OBJQIGCze4alzHRCTnBpCEvPe7MHDf1PPqeZkfyPfckAt9uGzAOCr1na3vQlGSu_uCbJopsan8ACuzC7djuSGhdWl45WbKyGQ3OMBKJhHiCbomWeqdILZUjc0XUDR89-gY6Vx55ToYkpkvbbnkY1Iym_zbiLnJ6ObqXXzg'}, {'domain': '.work.weixin.qq.com', 'httpOnly': True, 'name': 'wwrtx.sid', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': 'lanyrmqDIWwVSFavtSOE4dLkP4sDh7OYckB5fpHXBHuTV5_R2SIe8zy8MluKirtG'}, {'domain': '.work.weixin.qq.com', 'expiry': 1715517446, 'httpOnly': False, 'name': 'wwrtx.c_gdpr', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': '0'}]
# # 设置cookies绕过登录
# page_obj.my_add_cookies(cookies)
# time.sleep(5)
# page_obj.my_quit()

# driver = webdriver.Chrome(ChromeDriverManager().install())
# driver.get("https://work.weixin.qq.com/wework_admin/frame#index")
# # time.sleep(20)
# from config import cookies
# for cookie in cookies:
#     driver.add_cookie(cookie)
#
# time.sleep(2)
# driver.refresh()